<template>
  <a-modal :open="open" width="650px" title="撤销结束服务" centered ok-text="保存" destroy-on-close @ok="onOk" @cancel="onCancel">
    <div class="flex">
      <BaseTable
        :data-source="dataSource"
        height="292"
        row-key="id"
        :row-selection="{ selectedRowKeys, onChange: onCheckChange }"
        :columns="columns"
        :row-class-name="(record) => (record.isNew ? 'table-row-new' : '')"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'sycs'">
            <EditCell title="使用次数">
              <!-- <a-input v-model:value="record.sycs" v-input:int class="!text-right" placeholder="请输入" /> -->
              <a-input v-model:value="record.sycs" v-input:int class="!text-right" placeholder="请输入" @change="onChangeSl(record)" />
            </EditCell>
          </template>
        </template>
      </BaseTable>
    </div>
  </a-modal>
</template>
<script setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'

const emit = defineEmits(['update:open', 'success'])
const dataSource = ref([])
const selectedRowKeys = ref([])
const selectedRowData = ref([])
const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => ({})
  }
})
const columns = ref([
  { title: '服务项目', dataIndex: 'itemName' },
  { title: '登记次数', dataIndex: 'sl', align: 'right' },
  { title: '使用次数', dataIndex: 'sycs', align: 'right' }
])

const formState = ref({})

const onChangeSl = (record) => {
  selectedRowData.value.forEach((item) => {
    if (item.id === record.id) {
      item.sycs = record.sycs
    }
  })
}

const onCheckChange = (keys, data) => {
  selectedRowKeys.value = keys
  selectedRowData.value = data
}

const getTableData = async (lsh) => {
  const res = await post('course/courseRegister/getCourseRegisterDetailList', { lsh })
  if (res.code !== 0) return message.error(res.msg)
  dataSource.value = res.data.map((item) => {
    selectedRowKeys.value.push(item.id)
    selectedRowData.value.push(item)
    return {
      sycs: 0,
      ...item
    }
  })
}
watch(
  () => props.open,
  (val) => {
    if (val) {
      if (props.rowData?.lsh) {
        formState.value = { ...props.rowData }
        getTableData(formState.value.lsh)
      } else {
        formState.value = {}
        dataSource.value = []
        selectedRowKeys.value = []
        selectedRowData.value = []
      }
    }
  }
)

const onOk = async () => {
  selectedRowData.value.forEach((item) => {
    if (!item.sycs) {
      item.sycs = '0'
    }
  })
  const res = await post('course/courseRegister/doCancelCourseRegisterInfo', selectedRowData.value)
  if (res.code === 0) {
    message.success(res.msg)

    emit('success')
    onCancel()
  } else {
    message.error(res.msg)
  }
}

const onCancel = () => {
  emit('update:open', false)
}
</script>
<style lang="less" scoped></style>
